import BasicPage from '@/components/BasicPage'
import { BasicTable, TableListQueryParams, useTable } from '@/components/BasicTable'
import { ProColumns } from '@ant-design/pro-components'
import useConfirm from '@/hooks/useConfirm'
import { useModal } from '@/components/BasicModal'
import AddUserModal from './components/AddUserModal'
import { Button, Switch } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import RolePermissionModal from './components/RolePermissionModal'
import { useDrawer } from '@/components/BasicDrawer'
import UpdatePasswordDrawer from './components/UpdatePasswordDrawer'
import { userDeleteUserIdApi, userListApi, userStatusUserIdStatusApi } from '@/apis/payment'
import useMessage from '@/hooks/useMessage'
import { UserVO } from '@/apis/payment.type'

export default function UserManagement() {
  const { message } = useMessage()
  const { deleteConfirm, confirm } = useConfirm()
  const { tableAction, getProTableResponse } = useTable()
  const [registerAddModal, { openModal: openAddModal }] = useModal()
  const [registerRolePermissionModal] = useModal()

  const [registerUpdatePwdDrawer, { openDrawer: openUpdatePwdDrawer }] = useDrawer()

  const columns: ProColumns<UserVO>[] = [
    { title: '序号', valueType: 'index', width: 50 },
    { title: '用户名称', dataIndex: 'username' },
    { title: '姓名', dataIndex: 'realName', hideInSearch: true },
    { title: '角色', dataIndex: 'roleNames', hideInSearch: true },
    { title: '创建时间', dataIndex: 'createTime', hideInSearch: true },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 80,
      valueType: 'switch',
      render: (_, record) => (
        <Switch
          defaultChecked={!!record?.status}
          checkedChildren="启用"
          unCheckedChildren="停用"
          onChange={(e) => onChangeStatus(e, record?.userId)}
        />
      )
    },
    {
      title: '操作',
      valueType: 'option',
      width: 160,
      render: (_, record) => [
        <a key="edit" onClick={() => onEdit(record)}>
          编辑
        </a>,
        <a key="delete" className="delete" onClick={() => onDelete(record?.userId)}>
          删除
        </a>,
        <a key="resetPwd" className="delete" onClick={() => onResetPassword(record)}>
          重置密码
        </a>
      ]
    }
  ]

  async function getTableList(params: TableListQueryParams) {
    const resp = await userListApi({ userPageQuery: params })
    return getProTableResponse(resp)
  }

  function onResetPassword(record: UserVO) {
    openUpdatePwdDrawer(record)
  }

  function onEdit(record: UserVO) {
    openAddModal(record)
  }

  function onDelete(userId?: number) {
    deleteConfirm({
      onOk: async () => {
        if (!userId) return message.error('请选择要删除的用户')
        const { success } = await userDeleteUserIdApi({ userId })
        if (success) {
          message.success('删除成功')
          refleshTable()
        }
      }
    })
  }

  async function onChangeStatus(e: any, userId?: number) {
    confirm({
      title: '是否确认修改用户状态？',
      content: '确认',
      onOk: async () => {
        if (!userId) return message.error('请选择要修改的用户')
        const { success } = await userStatusUserIdStatusApi({ userId, status: e ? 1 : 0 })
        if (success) {
          message.success('修改成功')
          refleshTable()
        }
      }
    })
  }

  function refleshTable() {
    tableAction.current?.reload()
  }

  return (
    <BasicPage>
      <BasicTable
        request={getTableList}
        proTableProps={{
          columns,
          options: false,
          actionRef: tableAction,
          headerTitle: '用户列表',
          toolBarRender: () => [
            <Button type="primary" onClick={() => openAddModal()} icon={<PlusOutlined />}>
              新增用户
            </Button>
          ]
        }}
      />

      <AddUserModal register={registerAddModal} onFinished={refleshTable} />
      <RolePermissionModal register={registerRolePermissionModal} onFinished={refleshTable} />
      <UpdatePasswordDrawer register={registerUpdatePwdDrawer} onFinished={refleshTable} />
    </BasicPage>
  )
}
